import React, { PureComponent } from 'react'
import { Modal, Form, Input, Row, Col, Select, Radio, Cascader } from 'antd'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import usersActions from 'actions/users'

import Style from './customGoodsModal.css'

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

// let timeout
// let currentValue

// function fetch (value, callback) {
//   if (timeout) {
//     clearTimeout(timeout)
//     timeout = null
//   }
//   currentValue = value

//   function getUsers () {
//     usersActions.getUserList({
//       pageNo: 1,
//       pageSize: 999,
//       name: value
//     }).then(res => {
//       if (res.success && currentValue === value) {
//         callback(res.data.userResList || [])
//       }
//     })
//   }

//   timeout = setTimeout(getUsers, 300)
// }

class customGoodsModal extends PureComponent {
  static propTypes = {
    visible: PropTypes.bool,
    form: PropTypes.object,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
    getCategoryTree: PropTypes.func,
    getAuthorList: PropTypes.func,
    categoryTreeOptions: PropTypes.any,
    authorOptionsList: PropTypes.any,
    addressList: PropTypes.array,
    getAddressList: PropTypes.func
  }

  constructor (props) {
    super(props)
    this.state = {
      namePath: '',
      userOptions: []
    }
  }

  componentDidMount () {
    this.props.getAuthorList()
    this.props.getCategoryTree()
  }

  handleSearch = async value => {
    if (value) {
      const res = await usersActions.getUserList({
        pageNo: 1,
        pageSize: 999,
        mobile: value
      })
      if (res.success) {
        this.setState({
          userOptions: res.data.userResList || []
        })
      }
      // fetch(value, data => {
      //   this.setState({
      //     userOptions: data
      //   })
      // })
    } else {
      this.setState({
        userOptions: []
      })
    }
  }

  handleCancel =() => {
    const { onCancel } = this.props
    onCancel()
  }

  handleOk = () => {
    const { onOk, form } = this.props
    const { namePath } = this.state
    form.validateFields((err, values) => {
      if (!err) {
        const temp = {
          ...values,
          authorId: values.authorNode.key,
          authorName: values.authorNode.label,
          namePath,
          codePath: values.codePath.join(':'),
          price: values.price * 100
        }
        delete temp.authorNode
        onOk(temp)
      }
    })
  }

  handleSelectCategory = (value, selectedOptions) => {
    this.setState({
      namePath: selectedOptions.map(n => n.name).join(':')
    })
  }

  handleSelectUser = value => {
    const { getAddressList } = this.props
    getAddressList({
      userId: value
    })
  }

  render () {
    const { form, visible, authorOptionsList, categoryTreeOptions, addressList = [], confirmLoading } = this.props
    const { getFieldDecorator, getFieldValue } = form
    const formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      }
    }
    const itemLayout = {
      labelCol: {
        sm: { span: 6 }
      },
      wrapperCol: {
        sm: { span: 18 }
      }
    }

    const options = this.state.userOptions.map(n => <Option key={n.userId} value={n.userId}>{n.name}</Option>)

    return (
      <Modal
        title='订单-定制商品'
        visible={visible}
        confirmLoading={confirmLoading}
        onCancel={this.handleCancel}
        onOk={this.handleOk}
        width='1148px'
      >
        <Form {...formLayout}>
          <div className={Style['goods']}>

            <div className={Style['title']}>定制商品</div>
            <Item label='商品名称'>
              {getFieldDecorator('commodityName', {
                rules: [{ required: true, message: '请选择' }]
              })(<Input placeholder='请输入' style={{ width: 250, marginLeft: 10 }} />)}
            </Item>
            <Item label='用户'>
              {getFieldDecorator('userId', {
                rules: [{ required: true, message: '请输入' }],
                onChange: this.handleSelectUser
              })(<Select notFoundContent={null} filterOption={false} defaultActiveFirstOption={false} showSearch showArrow={false} placeholder='请输入手机号搜索' onSearch={this.handleSearch} style={{ width: 250, marginLeft: 10 }} >
                {options}
              </Select>)}
            </Item>
            <Item label='收货地址'>
              {getFieldDecorator('addressId', {
                rules: [{ required: true, message: '请输入' }]
              })(<Select placeholder='请选择' style={{ width: 250, marginLeft: 10 }} >
                {addressList.map(n => {
                  return <Option key={n.addressId} value={n.addressId}>{`${n.belongArea}${n.addressDetails}`}</Option>
                })}
              </Select>)}
            </Item>
            <Item label='分类'>
              {getFieldDecorator('codePath', {
                rules: [{ required: true, message: '请输入' }],
                onChange: this.handleSelectCategory
              })(<Cascader options={categoryTreeOptions} fieldNames={{ label: 'name', value: 'code', children: 'childList' }} style={{ width: 250, marginLeft: 10 }} />)}
            </Item>
            <Item label='创作者'>
              {getFieldDecorator('authorNode', {
                rules: [{ required: true, message: '请输入' }]
              })(<Select style={{ width: 250, marginLeft: 10 }} labelInValue placeholder='请选择创作者'>
                {authorOptionsList && authorOptionsList.map(n => {
                  return (<Option key={n.authorId} value={n.authorId} label={n.authorName} >{n.authorName}</Option>)
                })}
              </Select>)}
            </Item>
            <Item label='价格'>
              {getFieldDecorator('price', {
                rules: [{ required: true, message: '请输入' }, { pattern: /^\d*\.?\d*$/, message: '请输入正确的金额' }]
              })(<Input prefix='¥' placeholder='请输入' style={{ width: 250, marginLeft: 10 }} />)}
            </Item>
            <Item label='规格'>
              {getFieldDecorator('spec', {
                rules: [{ required: true, message: '请输入' }]
              })(<Input placeholder='请输入' style={{ width: 250, marginLeft: 10 }} />)}
            </Item>
            <Item label='数量'>
              <Input disabled placeholder='请输入' defaultValue={1} style={{ width: 250, marginLeft: 10 }} />
              {/* {getFieldDecorator('commodityName', {
                rules: [{ required: true, message: '请输入' }],
                initialValue: 1
              })()} */}
            </Item>
            <Item label='修改备注' className={Style['textarea']}>
              {getFieldDecorator('remark', {
                rules: [{ required: true, message: '请输入' }]
              })(<TextArea style={{ width: 350, marginLeft: 10 }} />)}
            </Item>
          </div>
          <Item label='是否申请开票' {...formLayout}>
            {getFieldDecorator('billFlag', {
              initialValue: 0
            })(<Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>)}
          </Item>
          {getFieldValue('billFlag') === 1 && (<>
            <div className={Style['title']}>发票信息</div>
            <Row gutter={20}>
              <Col span={9}>
                <Item {...itemLayout} label='发票类型'>
                  {getFieldDecorator('billNode.type', {
                    rules: [{ required: true, message: '请输入' }]
                  })(<Select >
                    <Option value='digit' >电子发票</Option>
                    <Option value='paper' >纸质发票</Option>
                  </Select>)}
                </Item>
              </Col>
              <Col span={9}>
                <Item {...itemLayout} label='发票抬头'>
                  {getFieldDecorator('billNode.title', {
                    rules: [{ required: true, message: '请输入' }]
                  })(<Input />)}
                </Item>
              </Col>
            </Row>
            <Row gutter={20}>
              <Col span={9}>
                <Item {...itemLayout} label='抬头类型'>
                  {getFieldDecorator('billNode.titleType', {
                    rules: [{ required: true, message: '请输入' }]
                  })(<Select>
                    <Option value='person'>个人</Option>
                    <Option value='company'>企业</Option>
                  </Select>)}
                </Item>
              </Col>
              {getFieldValue('billNode.titleType') === 'company' && <Col span={9}>
                <Item {...itemLayout} label='税号'>
                  {getFieldDecorator('billNode.no', {
                    rules: [{ required: true, message: '请输入' }]
                  })(<Input />)}
                </Item>
              </Col>}
            </Row>
            <Row>
              <Col span={9}>
                <Item {...itemLayout} label='收票人邮箱'>
                  {getFieldDecorator('billNode.email', {
                    rules: [{ required: true, message: '请输入' }]
                  })(<Input />)}
                </Item>
              </Col>
            </Row>
          </>)}
        </Form>
      </Modal>
    )
  }
}

const mapState = state => ({
  authorOptionsList: state.goods.authorOptionsList,
  categoryTreeOptions: state.order.categoryTreeOptions,
  userOptions: state.order.userOptions,
  addressList: state.order.addressList
})
const mapDispatch = dispatch => ({
  getCategoryTree: dispatch.order.getCategoryTree,
  getAuthorList: dispatch.goods.getAuthorList,
  getUserOptions: dispatch.order.getUserOptions,
  getAddressList: dispatch.order.getAddressList
})

export default connect(
  mapState,
  mapDispatch
)(Form.create()(customGoodsModal))
